<!-- eslint-disable vue/valid-v-for -->
<template>
  <el-row :gutter="20">
    <!-- 左侧标签树 -->
    <el-col :span="6" :xs="24">
      <ContentWrap class="h-1/1">
        <div class="head-container" style="text-align: center;">
          <el-button style="margin: 0 auto" type="primary" @click="addLabel">新增</el-button>
          <el-tree
            style="max-width: 600px;margin-top: 20px;"
            ref="treeRef"
            :data="labelList"
            :expand-on-click-node="false"
            :props="props"
            highlight-current
            node-key="id"
            :load="getList"
            @node-click="selectTree"
            lazy
          >
            <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span>
                    <Plus @click="addLabel(node,data)" style="width: 1em; height: 1em; margin-right: 8px" />
                    <Edit @click="editLabel(node,data)" style="width: 1em; height: 1em; margin-right: 8px" />
                    <Delete @click="deleteLabel(node,data)" style="width: 1em; height: 1em; margin-right: 8px" />
                  </span>
                </span>
            </template>
          </el-tree>
        </div>
      </ContentWrap>
    </el-col>
    <el-col :span="18" :xs="24">
      <ContentWrap>
        <el-button @click="addRule"><Icon icon="ep:plus" class="mr-5px" /> 添加规则</el-button>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="ruleList">
          <el-table-column align="left" label="规则" prop="rule"/>
          <el-table-column align="center" label="操作" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="updateRule(scope.row.id)"
              >
                修改
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteRule(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </el-col>
  </el-row>
  <LabelForm ref="labelFormRef" @success="getLabel"></LabelForm>
  <RuleForm ref="ruleFormRef" @success="getRuleList"></RuleForm>
</template>
<script lang="ts" setup>
import {defaultProps, handleTree} from '@/utils/tree'
import * as LabelApi from '@/api/label'
import {CommonStatusEnum} from '@/utils/constants'
import {ref} from "vue";
import ContentWrap from "@/components/ContentWrap/src/ContentWrap.vue";
import LabelForm from "@/views/infra/label/LabelForm.vue"
import {ElMessage, ElMessageBox} from "element-plus";
import {remove} from "@/api/knowledgeSystem/system";
import RuleForm from "@/views/infra/label/RuleForm.vue"

defineOptions({ name: 'LabelIndex' })

const formData = ref({
  pid: 0,
  pname: undefined,
  name: undefined,
  code: undefined,
  remark: undefined,
  sort: 0,
  status: 0
})

const props = {
  label: 'name',
  isLeaf: 'lazy',
}

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const labelFormRef = ref()
const ruleFormRef = ref()
const labelList = ref([])
const selectNode = ref()

const labelTree = ref([]) // 树形结构
const getLabel = async () => {
  labelList.value = await LabelApi.list(formData.value)
}
const labelType = ref([]) // 标签标签列表
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRules = reactive({
  name: [{required: true, message: '标签名称不能为空', trigger: 'blur'}],
  labelType: [{required: true, message: '标签标签不能为空', trigger: 'blur'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调


const addLabel = (node,data) => {
  if(node) {
    labelFormRef.value.open('create', node, 0)
  }{
    labelFormRef.value.open('create', {pid:0, pname:'无'}, 0)
  }
}

const editLabel = (node,data) => {
  labelFormRef.value.open('update', node, node.data.id)
}

const deleteLabel = (node,data) => {
  ElMessageBox.confirm('确定删除'+node.data.name+'吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 用户点击了确认按钮
    await LabelApi.remove(node.data.id)
    await getLabel()
  }).catch(() => {
    // 用户点击了取消按钮
    console.log('取消删除');
  });
}
const deleteRule = (id) => {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 用户点击了确认按钮
    await LabelApi.removeRule(id)
    await getRuleList()
  }).catch(() => {
    // 用户点击了取消按钮
    console.log('取消删除');
  });
}
const addRule = () => {
  console.log(selectNode.value)
  if(selectNode.value){
    ruleFormRef.value.open('create',selectNode.value,0)
  }else{
    ElMessage.info('请选择标签!')
  }
}
const updateRule = (id) =>{
  ruleFormRef.value.open('update',selectNode.value,id)
}
const ruleList = ref([])
const selectTree = async (node) => {
  selectNode.value = node
  const res = await LabelApi.ruleList({labelId: node.id})
  ruleList.value = res.list
}
const getRuleList = async () => {
  const res = await LabelApi.ruleList({labelId: selectNode.value.id})
  ruleList.value = res.list
}
let time = 0
const getList = async (node: Node,resolve: (data: Tree[]) => void, reject: () => void) => {
  console.log(node.data.id)
  if (node.level >= 1) {
    console.log(node.level)
    return resolve(await LabelApi.list({pid: 1}))
  }
}
/** 初始化 **/
onMounted(async () => {
  await getLabel()
})
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
